package com.qianxx.view.xrecyclerview;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by X on 2017/6/15.
 * <p>
 * 开启和禁止加载功能待优化
 * 设置 SwipeRefresh 圈圈颜色
 */
public class XRecyclerView extends SwipeRefreshLayout implements SwipeRefreshLayout.OnRefreshListener, IXRecyclerViewListener {

    private RecyclerView mRecyclerView;
    /**
     * 刷新监听
     */
    private IXRecyclerViewListener mListener;
    /**
     * 加载更多
     */
    private boolean isLoadMore = true;
    /**
     * 是否加载中
     */
    private boolean isLoading = false;
    /**
     * 是否向下滑动
     */
    private boolean isSlideDown = false;

    private XRecyclerViewAdapter mXRecyclerViewAdapter;

    public XRecyclerView(Context context) {
        this(context, null);
    }

    public XRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mRecyclerView = new RecyclerView(context);
        addView(mRecyclerView);

        initListener();
    }

    private void initListener() {
        addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                mRecyclerView.getLayoutParams().width = LayoutParams.MATCH_PARENT;
                mRecyclerView.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
            }

            @Override
            public void onViewDetachedFromWindow(View v) {

            }
        });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!isLoadMore) {
                    return;
                }

                int lastPosition = -1;
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                    if (layoutManager instanceof GridLayoutManager) {
                        lastPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
                    } else if (layoutManager instanceof LinearLayoutManager) {
                        lastPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                    } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                        int[] lastPositions = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
                        ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(lastPositions);
                        lastPosition = findMax(lastPositions);
                    }

                    if (lastPosition == recyclerView.getLayoutManager().getItemCount() - 1 && isSlideDown) {
                        if (!isLoading) {
                            onLoadMore();
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                isSlideDown = dy >= 0;
            }

            private int findMax(int[] lastPositions) {
                int max = lastPositions[0];
                for (int value : lastPositions) {
                    if (value > max) {
                        max = value;
                    }
                }
                return max;
            }
        });

        setOnRefreshListener(this);
    }

    public void setLayoutManager(RecyclerView.LayoutManager manager) {
        mRecyclerView.setLayoutManager(manager);
    }

    public void setXRecyclerViewListener(IXRecyclerViewListener listener) {
        mListener = listener;
    }

    public void setLoadEnable(boolean enable) {
        isLoadMore = enable;
        if (!enable) {
            mXRecyclerViewAdapter.getXFooterView().hideView();
            setXRecyclerViewListener(null);
        }
    }

    public void setAdapter(RecyclerView.Adapter adapter) {
        mXRecyclerViewAdapter = new XRecyclerViewAdapter(getContext(), adapter);
        adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                mXRecyclerViewAdapter.notifyDataSetChanged();
            }
        });
        mXRecyclerViewAdapter.setLoadMore(isLoadMore);
        mRecyclerView.setAdapter(mXRecyclerViewAdapter);
    }

    @Override
    public void onRefresh() {
        setRefreshing(true);
        isLoadMore = false;
        if (mListener != null) {
            mListener.onRefresh();
        }
    }

    @Override
    public void onLoadMore() {
        setLoading();
        if (mListener != null) {
            mListener.onLoadMore();
        }
    }

    public void refreshComplete() {
        setRefreshing(false);
        // 初始化加载更多布局
        isLoadMore = true;
        mXRecyclerViewAdapter.getXFooterView().initView();
    }

    public void loadFailed(){
        refreshComplete();
        mXRecyclerViewAdapter.getXFooterView().loadFailed();
    }

    public void setLoading() {
        isLoading = true;
        mXRecyclerViewAdapter.getXFooterView().loading();
    }

    public void setLoadComplete(boolean noData) {
        isLoading = false;
        if (noData) {
            isLoadMore = false;
            mXRecyclerViewAdapter.getXFooterView().loadComplete();
        } else {
            isLoadMore = true;
            mXRecyclerViewAdapter.getXFooterView().initView();
        }
    }

    public void setLoadHide() {
        isLoading = false;
        isLoadMore = false;
        mXRecyclerViewAdapter.getXFooterView().hideView();
    }
}
